import { addUserPermissionApi, updateUserPermissionApi } from '@/services/api';
import {
  DrawerForm,
  ProFormInstance,
  ProFormItem,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Form, Radio, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useRef } from 'react';
interface Props {
  open?: boolean;
  info?: any;
  close?: () => void;
  onFinish?: () => void;
  type?: string;
}

const CreateBindRuleDrawer: React.FC<Props> = ({
  open,
  close,
  info,
  onFinish,
  type,
}) => {
  const [form] = Form.useForm();

  const formRef = useRef<ProFormInstance>();

  return (
    <DrawerForm
      formRef={formRef}
      title={info.id ? '编辑权限' : '新建权限'}
      form={form}
      open={open}
      width={'38%'}
      onOpenChange={(visible) => {
        if (!visible) {
          close?.();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      initialValues={{ ...info }}
      onFinish={async (values) => {
        console.log('type', type);

        try {
          // 如果是新增
          if (type === 'add') {
            const { msg } = await addUserPermissionApi({
              ...values,
              parent: info.id ? info.id : undefined,
              // parent_id: ''
            });

            message.success(msg);
          } else {
            const { msg } = await updateUserPermissionApi(info?.id, {
              ...values,
            });

            message.success(msg);
          }

          onFinish?.();
          // 不返回不会关闭弹框
          return true;
        } catch (error) {}
      }}
    >
      <ProFormItem
        name="leaf"
        label="权限类型"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <Radio.Group buttonStyle="solid">
          <Radio.Button value={false}>菜单权限</Radio.Button>
          <Radio.Button value={true}>按钮权限</Radio.Button>
        </Radio.Group>
      </ProFormItem>

      <ProFormText
        width="lg"
        name="value"
        label="权限码"
        placeholder="请输入权限码"
        rules={[
          {
            required: true,
          },
        ]}
      />

      <ProFormTextArea
        width="lg"
        name="label"
        label="权限名称"
        placeholder="请输入权限名称"
        rules={[
          {
            required: true,
          },
        ]}
      />
    </DrawerForm>
  );
};

export default React.memo(CreateBindRuleDrawer, (prev, next) =>
  isEqual(prev, next),
);
